﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.ModelBinding;
using Wechat.Util.Error;

namespace Wechat.Util.ModelStates
{
    /// <summary>
    /// 实体校验状态扩展
    /// </summary>
    public static class ModelStateExtend
    {
        /// <summary>
        /// 获取全部实体状态错误信息
        /// </summary>
        /// <param name="modelState"></param>
        /// <returns></returns>
        public static IEnumerable<ShowError> AllModelStateErrors(this ModelStateDictionary modelState)
        {
            var result = new List<ShowError>();

            //找到出错的字段以及出错信息
            var errorFieldsAndMsgs = modelState.Where(m => m.Value.Errors.Any())
                .Select(m => new { m.Key, m.Value.Errors });

            foreach (var item in errorFieldsAndMsgs)
            {
                //获取键
                var fieldKey = item.Key;

                //获取键对应的错误信息
                var fieldErrors = item.Errors
                    .Select(e => new ShowError(fieldKey, e.ErrorMessage));

                result.AddRange(fieldErrors);
            }
            return result;
        }
    }
}
